﻿using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using TaskQueueDemo.Commands;
using TaskStatus = TaskQueueDemo.ViewModel.TaskStatus;
namespace TaskQueueDemo.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        public TaskQueueManager TaskManager { get; } = new TaskQueueManager();

        private ICommand _addTaskCommand;
        public ICommand AddTaskCommand => _addTaskCommand ??= new RelayCommand(AddTask);

        private ICommand _startTasksCommand;
        public ICommand StartTasksCommand => _startTasksCommand ??= new RelayCommand(StartTasks);

        private ICommand _cancelTaskCommand;
        public ICommand CancelTaskCommand => _cancelTaskCommand ??= new RelayCommand<TaskItem>(CancelTask);


        private ICommand _ClearCompletedTasksCommand;
        private ICommand _CopyLogsCommand;
        public ICommand CopyLogsCommand => _CopyLogsCommand ??= new RelayCommand<TaskItem>(CopyLogs);
        private ICommand _stopAllTasksCommand;
        public ICommand StopAllTasksCommand => _stopAllTasksCommand ??= new RelayCommand(StopAllTasks);
        
        public ICommand ClearCompletedTasksCommand =>
            _ClearCompletedTasksCommand ??= new RelayCommand(() =>
            {
                TaskManager.ClearCompletedTasks();
            });
        public int[] PossibleConcurrencyLevels => new[] { 1, 2, 3, 4, 5, 10 };

        private void AddTask()
        {
            int taskNumber = TaskManager.Tasks.Count + 1;
            TaskManager.AddTask($"任务 {taskNumber}", (token, progress) =>
            {
                for (int i = 0; i <= 100; i++)
                {
                    token.ThrowIfCancellationRequested();
                    System.Threading.Thread.Sleep(50);
                    
                    progress.Report(i);
                }
            });
        }

        private void StartTasks()
        {
            TaskManager.StartProcessing();
        }

        private void CancelTask(TaskItem task)
        {
            task.Cancel();
        }
        private void CopyLogs(TaskItem task)
        {
            Clipboard.SetText(task.CopyLogs());
            MessageBox.Show(task.CopyLogs());
        }

        private void StopAllTasks()
        {
            TaskManager.StopAllTasks();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}